﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SolutionModel;
using System.Data.SqlClient;
using System.Data;
using System.Data.Objects;
using SFast.DB;
using SFast;
using SFast.Web;
using System.Transactions;
//using EntityFramework.Extensions;
using NLite.Data;
using System.Data.Common;

namespace SolutionDAL
{
    public class T_MenuDAL
    {

        #region 获取分类树

        /// <summary>
        /// 获取分类树
        /// </summary>
        /// <returns></returns>
        public List<T_Menu> GetTree()
        {
            return GetTree(0, 0);
        }
        #endregion

        #region 获取分类树 可以控制显示最大级别
        /// <summary>
        /// 获取分类树 可以控制显示最大级别
        /// </summary>
        /// <param name="MaxDepth">最大深度（不可高于，可等于此级别的分类）</param>
        /// <returns></returns>
        public List<T_Menu> GetTree(int MaxDepth)
        {
            return GetTree(0, MaxDepth);
        }
        #endregion

        #region 获取某段级别范围的分类树 可以控制显示最小和最大级别
        /// <summary>
        /// 获取分类树 可以控制显示最大级别
        /// </summary>
        /// <param name="MinDepth">最小深度（不可低于，可等于此级别的分类）</param>
        /// <param name="MaxDepth">最大深度（不可高于，可等于此级别的分类）</param>
        /// <returns></returns>
        public List<T_Menu> GetTree(int MinDepth, int MaxDepth)
        {
            PurviewDBEntities db = DBConfig.GetDBContext();
            if (MaxDepth == 0)
            {
                return db.T_Menus.Where(o => o.C_Depth >= MinDepth).OrderBy(o => o.C_Order).ToList<T_Menu>();
            }
            else
            {
                return db.T_Menus.Where(o => o.C_Depth <= MaxDepth & o.C_Depth >= MinDepth).OrderBy(o => o.C_Order).ToList<T_Menu>();
            }

        }
        #endregion

        #region  添加菜单
        /// <summary>
        /// 添加菜单
        /// 标记：需要修改
        /// </summary>
        /// <param name="obj"></param>
        public int InsertMenus(T_Menu obj)
        {
            int RowCount = 0;
            PurviewDBEntities dbe = DBConfig.GetDBContext();
            dbe.UsingTransaction(() =>
            {
                //添加菜单
                var rs = dbe.DbHelper.ExecuteNonQuery(" exec sp_Menus_Insert @C_Parent_ID,@C_Name,@C_Intro,@C_EnName,@C_Url",
                        new
                        {
                            C_Parent_ID = obj.C_Parent_ID,
                            C_Name = obj.C_Name,
                            C_Intro = obj.C_Intro,
                            C_EnName = obj.C_EnName,
                            C_Url = obj.C_Url
                        });
                #region  无用代码
                //var MenuIds = (from m in dbe.TMenuInRoles
                //         where m.Role.RoleName == "超级管理员"
                //        select m.MenuId)
                //        .ToArray();
                //var Menus = from m in dbe.TMenus
                //        where !MenuIds.Contains(m.CId)
                //        select m;
                #endregion

                //获取最高级角色ID
                var id = dbe.T_AdminRoles
                    .Where(o => o.RoleName == WebConfigOperation.GetAppSettings("SeniorRoleName"))
                    .Select(o => o.RoleID)
                    .FirstOrDefault();

                //查找最高级角色没有权限的菜单
                var q = from m in dbe.T_Menus
                        where !(from m1 in dbe.T_MenuInRoles
                                where m1.RoleID == id
                                select m1.MenuID).Contains(m.C_ID)
                        select m;

                var menu = q.FirstOrDefault();

                //默认给最高权限角色加入新菜单的权限
                RowCount = dbe.T_MenuInRoles.Insert(new T_MenuInRole { RoleID = id, MenuID = menu.C_ID });

            });
            return RowCount;
        }

        #endregion

        #region  通过菜单ID获取菜单
        /// <summary>
        /// 通过菜单ID获取菜单
        /// </summary>
        /// <param name="mid">菜单ID</param>
        /// <returns></returns>
        public IQueryable<T_Menu> GetMenuByID(int mid)
        {
            PurviewDBEntities db = DBConfig.GetDBContext();
            return db.T_Menus.Where(o => o.C_ID == mid);
        }

        #endregion

        #region  通过ID获取菜单并转为JS，用于回填写到表单中
        /// <summary>
        /// 通过ID获取菜单并转为JS，用于回填写到表单中
        /// 标记：需要修改
        /// </summary>
        /// <param name="mid">菜单ID</param>
        /// <returns></returns>
        public void GetMenuByIDToJs(int mid)
        {
            PurviewDBEntities db = DBConfig.GetDBContext();

            var a = from menu in db.T_Menus
                    join menu2 in db.T_Menus on menu.C_Parent_ID equals menu2.C_ID into menu3
                    from menu4 in menu3.DefaultIfEmpty()
                    where menu.C_ID == mid
                    select new
                    {
                        menu.C_ID,
                        menu.C_Depth,
                        menu.C_EnName,
                        menu.C_Intro,
                        menu.C_Name,
                        menu.C_Order,
                        menu.C_Parent_ID,
                        menu.C_Path,
                        menu.C_Url,
                        Pname = menu4.C_Name._HasVal("根目录")
                    };
            a.FirstOrDefault()._DataToForm("form1");

            //String sql = "SELECT tm.*, ISNULL(t.C_Name ,'根目录') AS Pname FROM dbo.T_Menus AS tm LEFT JOIN dbo.T_Menus AS t ON t.C_ID =tm.C_Parent_ID WHERE tm.C_ID='" + mid + "'";

            //return db.AutoFormOutPut(sql, "aspnetForm");
        }

        #endregion

        #region 通过父类获取第一级子级别的分类树
        /// <summary>
        /// 通过父类获取第一级子级别的分类树
        /// </summary>
        /// <param name="pid">父ID</param>
        /// <returns></returns>
        public IQueryable<T_Menu> GetTreeByPid(int pid)
        {
            PurviewDBEntities db = DBConfig.GetDBContext();
            return db.T_Menus.Where(o => o.C_Parent_ID == pid).OrderBy(o => o.C_Order);
        }

        #endregion

        #region 通过ID更新分类数据
        /// <summary>
        /// 标记需要修改
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int UpdateMenu(T_Menu obj)
        {
            PurviewDBEntities db = DBConfig.GetDBContext();

            return db.DbHelper.ExecuteNonQuery("exec sp_Menus_Update @C_ID,@C_Parent_ID,@C_Name,@C_Intro,@C_Order,@C_EnName,@C_Url",
                new
                {
                    C_ID = obj.C_ID,
                    C_Parent_ID = obj.C_Parent_ID,
                    C_Name = obj.C_Name._HasVal(""),
                    C_Intro = obj.C_Intro._HasVal(""),
                    C_Order = obj.C_ID,
                    C_EnName = obj.C_EnName._HasVal(""),
                    C_Url = obj.C_Url._HasVal("")
                }
                );


            //SqlParameter[] par ={
            //                        new SqlParameter("@C_ID",obj.CId),
            //                        new SqlParameter("@C_Parent_ID",obj.CParentId),
            //                        new SqlParameter("@C_Name",obj.CName._HasVal("")),
            //                        new SqlParameter("@C_Intro",obj.CIntro._HasVal("")),
            //                        new SqlParameter("@C_Order",obj.CId),
            //                        new SqlParameter("@C_EnName",obj.CEnName._HasVal("")),
            //                        new SqlParameter("@C_Url",obj.CUrl._HasVal("")),
            //                   };

            //return db.Exec_SP_Query("sp_Menus_Update", par);

        }

        #endregion

        #region 同级排序

        /// <summary>
        /// 同级排序
        /// 标记，需要修改
        /// </summary>
        /// <param name="cid">当前需要变换位置的菜单ID</param>
        /// <param name="targetid">新位置的ID，也就是说，当前ID所要替换谁新位置的ID的位置</param>
        public void SortMenu(int cid, int targetid,int pid)
        {
            DbExecuter db = new DbExecuter();
            var obj = GetMenuByID(cid).FirstOrDefault();  //获取本身信息

            SqlParameter[] par ={
                                    new SqlParameter("@C_ID",obj.C_ID),
                                    new SqlParameter("@C_Parent_ID",pid),
                                    new SqlParameter("@C_Name", obj.C_Name._HasVal("")),
                                    new SqlParameter("@C_Intro",obj.C_Intro._HasVal("")),
                                    new SqlParameter("@C_Order",targetid),  //目标排序位置
                                    new SqlParameter("@C_EnName",obj.C_EnName._HasVal("")),
                                    new SqlParameter("@C_Url",obj.C_Url._HasVal("")),
                               };

            db.Exec_SP_Query("sp_Menus_Update", par);
        }

        #endregion

        #region 判断当前的菜单父ID是否为自己或自己的所有子菜单ID
        /// <summary>
        /// 编辑时，选择父类菜单时， 判断当前的选择项是否为自己或自己的所有子菜单ID
        /// 不可把“菜单本身”或“子菜单”当做本菜单的“父菜单”，请重新选择父菜单项！
        /// </summary>
        /// <param name="ParentID">父ID</param>
        /// <param name="MenuID">当前菜单ID</param>
        /// <returns></returns>
        public int VerifyParent(int ParentID, int MenuID)
        {
            PurviewDBEntities db = DBConfig.GetDBContext();
            string mid = MenuID.ToString();
            return db.T_Menus.Where(p => ("|" + p.C_Path + "|").Contains("|" + mid + "|") & p.C_ID == ParentID).Count();

        }
        #endregion

        #region 删除菜单
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="menuID"></param>
        public void delMenuID(int menuID)
        {
            PurviewDBEntities dbe = DBConfig.GetDBContext();
            dbe.UsingTransaction(() =>
            {
                try
                {
                    //删除角色跟菜单的之间的关系
                    dbe.T_MenuInRoles.Delete(o => o.MenuID == menuID);


                    dbe.DbHelper.ExecuteNonQuery("exec sp_Menus_Delete @C_ID", new { C_ID = menuID });
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            });
        }
        #endregion

        #region 通过用户ID获取该用户有权限访问的菜单列表
        /// <summary>
        /// 通过用户ID获取该用户有权限访问的菜单列表
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public List<T_Menu> getMenuByUsesrID(String uid)
        {
            PurviewDBEntities dbe = DBConfig.GetDBContext();
            var q = dbe.T_Menus
                    .Join(dbe.T_MenuInRoles, r1 => r1.C_ID, r2 => r2.MenuID, (r1, r2) => new { r1, RoleID = r2.RoleID })
                    .Join(dbe.T_UsersInRoles, u1 => u1.RoleID, u2 => u2.RoleID, (u1, u2) => new { u1, UserId = u2.UserID })
                    .Where(o => o.UserId == uid)
                    .Select(o => o.u1.r1)
                    .Distinct()
                    .OrderBy(o => o.C_Order);

            return q.ToList();

        }
        #endregion

    }
}

